package com.sl.biz.core.runner.thread;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.thread.RejectPolicy;
import cn.hutool.core.util.StrUtil;
import com.sl.biz.modular.thread.dao.domain.dto.ProcessThreadConfigDTO;
import com.sl.biz.modular.thread.dao.service.ProcessThreadConfigDaoService;
import com.sl.core.engine.thread.ThreadConfig;
import com.sl.core.engine.thread.TraceThreadPoolTaskExecutor;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
public class ThreadConfigRunner implements CommandLineRunner {

    private final ProcessThreadConfigDaoService configDaoService;

    @Override
    public void run(String... args) {
        List<ProcessThreadConfigDTO> configDTOList = configDaoService.queryEnabledList();
        if (CollUtil.isEmpty(configDTOList)) {
            return;
        }

        for (ProcessThreadConfigDTO processThreadConfigDTO : configDTOList) {
            Integer corePoolSize = processThreadConfigDTO.getCorePoolSize();
            Long keepAliveTime = processThreadConfigDTO.getKeepAliveTime();
            Long queueCapacity = processThreadConfigDTO.getQueueCapacity();
            String threadName = processThreadConfigDTO.getThreadName();
            if (StrUtil.isBlank(threadName)) {
                threadName = "process-default";
            }
            String timeUnit = processThreadConfigDTO.getTimeUnit();
            if (StrUtil.isBlank(timeUnit)) {
                timeUnit = TimeUnit.MILLISECONDS.name();
            }
            String rejectPolicy = processThreadConfigDTO.getRejectPolicy();
            if (StrUtil.isBlank(rejectPolicy)) {
                rejectPolicy = RejectPolicy.ABORT.name();
            }
            String threadCode = processThreadConfigDTO.getThreadCode();
            Integer maximumPoolSize = processThreadConfigDTO.getMaximumPoolSize();
            TraceThreadPoolTaskExecutor threadPoolTaskExecutor = new TraceThreadPoolTaskExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.valueOf(timeUnit), queueCapacity.intValue(), threadName);
            threadPoolTaskExecutor.setRejectedExecutionHandler(RejectPolicy.valueOf(rejectPolicy).getValue());
            ThreadConfig.INSTANCE.put(threadCode, threadPoolTaskExecutor);
        }
    }
}
